<?php

namespace api\console\controllers;

use api\components\GeoService;
use api\components\Request;
use api\modules\app\models\MetaArea;
use api\modules\app\models\Qrcode;
use api\modules\app\models\QrcodeRecord;
use api\modules\app\models\Section;
use api\modules\app\models\Test;
use api\modules\app\models\TypeSync;
use api\modules\app\models\Unit;
use api\modules\app\services\ElasticSearchService;
use api\modules\app\services\QrcodeService;
use api\modules\app\services\UnitService;
use api\services\AreaService;
use yii\console\Controller;
use yii\db\Query;
use yii\helpers\ArrayHelper;

class SyncController extends Controller
{
    public function actionSyncArea($level = AreaService::META_LEVEL_1)
    {
        echo 'begin sync area_dict ...' . PHP_EOL;
        AreaService::sync($level);
        echo 'down sync area_dict ...' . PHP_EOL;
    }

    public function actionSyncEs()
    {
        ElasticSearchService::batchSync();
    }

    public function actionSection()
    {
        $url = \Yii::$app->params['es_end_point'] . "/united-ciimc-api/v1/generic-query";
        $params = [
            'token' => \Yii::$app->params['es_search_token'],
            'table' => 'arcgis',
            'index_type' => 'active',
            'limit' => '10000',
            'filter' => 'simple.messageType=eq.地面一般道路发布段',
            'district' => '静安区'
        ];
        $request = new Request();
        $response = $request->request($url . '?' . http_build_query($params), 'GET');
        if ($response) {
            $response = json_decode($response, true);
            if (isset($response['result']) && $response['result'] == 'success') {
                $data = $response['data']['messages'];
                if (!empty($data)) {
                    $keys = ['code', 'name', 'start', 'end', 'district_code', 'street_code', 'range', 'range_cd'];
                    $values = [];
                    foreach ($data as $row) {
                        $valueRow = [
                            $row['primeID'],
                            $row['args']['attributes']['路名'],
                            $row['args']['attributes']['起点交叉路'],
                            $row['args']['attributes']['终点交叉路'],
                            $row['args']['attributes']['区代码'],
                            $row['args']['attributes']['街道代码'],
                            isset($row['data']['polygons']) ? json_encode($row['data']['polygons'][0]['points']) : '',
                            json_encode($row['args']['geometry']['rings'][0])
                        ];
                        $values[] = $valueRow;
                    }
                    $trans = \Yii::$app->test_3->beginTransaction();
                    try {
                        Section::deleteAll();
                        \Yii::$app->test_3->createCommand()->batchInsert(Section::tableName(), $keys, $values)->execute();
                        $trans->commit();
                        echo '路段初始化完成。';
                        return true;
                    } catch (\Exception $e) {
                        $trans->rollBack();
                        echo '路段初始化失败。 失败原因：' . $e->getMessage();
                    }
                }
            }
        }
        echo '路段初始化失败。';
    }

    public function actionUnit()
    {
        $metas = MetaArea::findAll(['category' => '街道', 'status' => 1, 'parent_id' => 6]);
        $sync = TypeSync::find()->andFilterWhere(['status' => 1])->asArray()->all();
        $syncData = ArrayHelper::index($sync,'center_code');
        if(!empty($sync)) {
            if (!empty($metas)) {
                foreach ($sync as $s) {
                    $types = explode(',',$s['center_code']);
                    if(!empty($types)) {
                        foreach ($types as $type) {
                            foreach ($metas as $streetObj) {
                                $street = $streetObj->name;
                                $geoService = new GeoService();
                                $url = DATA_CENTER_HOST . "/district-platform-api/digit-housing-estate/units";
                                $params = [
                                    'token' => \Yii::$app->params['es_search_token2'],
                                    'filter' => 'housingEstate.rawIdentity=ex.true%26town.areaName=eq.' . $street . '%26simple.messageType=eq.' . $type,
                                ];
                                $request = new Request();
                                $url = $url . '?' . http_build_query($params);
                                echo $type . " 请求url：" . $url . "\r\n";
                                $response = $request->request($url, 'GET');
                                if ($response) {
                                    $response = json_decode($response, true);
                                    if (isset($response['result']) && $response['result'] == 'success') {
                                        $data = $response['data'];
                                        echo $type . '接口获取' . count($data) . '条数据。' . "\r\n";
                                        if (!empty($data)) {
                                            $keys = ['unit_code', 'outer_code', 'district_code', 'street_code',
                                                'community_code',
                                                'community_name',
                                                'estate_code',
                                                'estate_name',
                                                'event_type1',
                                                'event_type2',
                                                'event_type3',
                                                'event_type1_code',
                                                'event_type2_code',
                                                'event_type3_code',
                                                'grid_code',
                                                'name',
                                                'name_code',
                                                'lng', 'lat', 'lng_cd', 'lat_cd', 'lng_gcj', 'lat_gcj', 'address',
                                                'status', 'state', 'cuser', 'ctime', 'utime',
                                                'dep_code',
                                                'bind_iot',
                                                'iot_code',
                                                'def',
                                                'type_code'
                                            ];
                                            $values = [];
                                            $outs = [];
                                            foreach ($data as $row) {
                                                $unit = Unit::findOne(['outer_code' => $row['out_code']]);
                                                if (!$unit && !in_array($row['out_code'], $outs)) {
                                                    $outs[] = $row['out_code'];
                                                    list($lngGd, $latGd) = $geoService->gps2gcj($row['lng'], $row['lat']);
                                                    $params = [
                                                        'name_code' => $syncData[$s['center_code']]['name_code'],
                                                        'district_code' => $row['district_code'],
                                                        'street_code' => $row['street_code'],
                                                    ];
                                                    $valueRow = [
                                                        UnitService::generateCode($params, UnitService::INIT_MODE_META),
                                                        $row['out_code'],
                                                        $row['district_code'],
                                                        $row['street_code'],
                                                        $row['community_code'],
                                                        $row['community_name'],
                                                        $row['estate_code'],
                                                        $row['estate_name'],
                                                        $syncData[$s['center_code']]['event_type1'],
                                                        $syncData[$s['center_code']]['event_type2'],
                                                        $syncData[$s['center_code']]['event_type3'],
                                                        $syncData[$s['center_code']]['event_type1_code'],
                                                        $syncData[$s['center_code']]['event_type2_code'],
                                                        $syncData[$s['center_code']]['event_type3_code'],
                                                        $row['grid_code'],
                                                        $syncData[$s['center_code']]['name'],
                                                        $syncData[$s['center_code']]['name_code'],
                                                        $row['lng'],
                                                        $row['lat'],
                                                        $row['lng_cd'],
                                                        $row['lat_cd'],
                                                        $lngGd,
                                                        $latGd,
                                                        isset($row['address']) ? $row['address'] : '',
                                                        1,
                                                        1,
                                                        0,
                                                        time(),
                                                        time(),
                                                        $syncData[$s['center_code']]['manage_dep'],
                                                        0,
                                                        '',
                                                        1,
                                                        $type
                                                    ];
                                                    $values[] = $valueRow;
                                                }
                                            }
                                            $trans = \Yii::$app->test_3->beginTransaction();
                                            try {
                                                Unit::deleteAll(['type_code' => $type, 'channel' => 1,'street_code' => $streetObj->code]);
                                                \Yii::$app->test_3->createCommand()->batchInsert(Unit::tableName(), $keys, $values)->execute();
                                                $trans->commit();
                                                echo $type . '初始化完成。' . "\r\n";
                                            } catch (\Exception $e) {
                                                $trans->rollBack();
                                                echo $type . '初始化失败。 失败原因：' . $e->getMessage() . "\r\n";
                                            }
                                        } else {
                                            Unit::deleteAll(['name' => $type, 'channel' => 1]);
                                            echo $type . '接口无数据。' . "\r\n";
                                        }
                                    } else {
                                        echo $type . '接口返回格式错误。' . "\r\n";
                                    }
                                } else {
                                    echo $type . '接口无响应。' . "\r\n";
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    public function actionInitIot()
    {
        $rows = Test::find()->all();
        foreach ($rows as $row){
            $unitCode = $row->unit_code;
            $unit =  Unit::findOne(['unit_code' => $unitCode]);
            if($unit){
                $iotCode = $unit->iot_code;
                $iotCodeArr = $iotCode == '' ? [] : explode(',',$iotCode);
                $iotCodeArr[] = $row->iot_code;
                $unit->setAttributes([
                    'bind_iot' => 1,
                    'iot_code' => implode(',',$iotCodeArr)
                ]);
                $unit->save();
            }
        }
    }

    public function actionBind($batchCode, $dryRun = 1)
    {
        // street_code='0617' AND estate_code != 'XQ0600404'
        // $query = Unit::find()->where(['state' => 1, 'has_bind' => 0, 'street_code' => '0617'])
        //                      ->andFilterWhere(['!=', 'estate_code', 'XQ0600356']);
        $query = Unit::find()->where(['state' => 1, 'has_bind' => 0, 'street_code' => '0617', 'estate_code' =>'XQ0600404']);
        $count = $query->count();
        var_dump($count);
        if (!empty($dryRun)) {
            return;
        }
        $qrcodes = Qrcode::findAll(['batch_code' => $batchCode, 'has_bind' => 0]);
        $codes = ArrayHelper::getColumn($qrcodes, 'code');
        $qrcodeService = new QrcodeService();
        $index = 0;
        foreach ($query->each() as $item) {
            $qrcodeService->bind($codes[$index], ['unitCode' => $item['unit_code'], 'address' => ''], ['id' => 1, 'username' => 'admin']);
            $index++;
        }
    }

    public function actionBindCount()
    {
        $records = QrcodeRecord::findAll(['state' => 0]);
        foreach ($records as $record) {
            $record->bind_count = Qrcode::find()->where(['has_bind' => 1, 'batch_code' => $record->id])->count();
            $record->save();
        }
    }
}
